package ClientComm;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import Threads.QueueClient;
import java.awt.Point;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Dakota Brown, Travis Shuff
 * @since 10/20/11
 */
public class ConnectionObject {

    private static Connection conn;
    private static Statement stmnt;
    private ResultSet rs;
    private ArrayList<Robot> robotList = new ArrayList<Robot>();
    private static boolean builtID = false;
    private static boolean displayedConnectError = false;
    private String host, user, password, port;

    public ConnectionObject() {
    }

    /**
     * 
     * @param host
     * @param user
     * @param password
     * @param port 
     */
    public ConnectionObject(String host_In, String user_In, String password_In, String port_In) {
        this.host = host_In;
        this.user = user_In;
        this.password = password_In;
        this.port = port_In;
    }
    
    public String connectToDatabase(){
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://"+ host, user, password);
            if (!conn.isClosed()) {
                    stmnt = conn.createStatement(java.sql.ResultSet.TYPE_SCROLL_SENSITIVE, java.sql.ResultSet.CONCUR_UPDATABLE);
            }
        } catch (ClassNotFoundException ex) {
            return "MySQL Package Error";
        } catch (SQLException ex) {
            return "Error Connecting To Database";
        }
        
        return "Connection Successful";
    }
    
    public int getRobotsFromDB(){
        int robotCount = 0;
        try {
            if (!conn.isClosed()) {
                        stmnt = conn.createStatement(java.sql.ResultSet.TYPE_SCROLL_SENSITIVE, java.sql.ResultSet.CONCUR_UPDATABLE);
            }
            rs = stmnt.executeQuery("SELECT * FROM ARENA");
            while(rs.next()){
                robotList.add(new Robot(rs.getString("id"), new Point(rs.getInt("x"), rs.getInt("y")), rs.getString("heading").charAt(0)));
            }
        } catch (SQLException ex) {
            Logger.getLogger(ConnectionObject.class.getName()).log(Level.SEVERE, null, ex);
        }
        return robotCount;
    }
    
    public ArrayList<Robot> getRobotList(){
        return robotList;
    }
    
    public String buildID() {
        String id = "";
        for (int i = 0; i < 10; i++) {
            id += (char) ((int) (Math.random() * 25 + 65)); //65 - 90 because capital letters
        }
        try {
            while (conn == null) {
                try {
                    Thread.sleep(1);
                } catch (InterruptedException ex) {
                }
            }
            if (!conn.isClosed()) {
                stmnt = conn.createStatement(java.sql.ResultSet.TYPE_SCROLL_SENSITIVE, java.sql.ResultSet.CONCUR_UPDATABLE);
            }
            while (stmnt == null) {
            }
            stmnt.executeUpdate("INSERT INTO Queue (id, position, timestamp, connected) "
                    + "          VALUES ('" + id + "', '0', NULL, 't');");
            builtID = true;
        } catch (SQLException ex) {
            ex.printStackTrace();
        }

        return id;
    }
    
     public void updateConnectivity(String id){
        try {
            stmnt.executeUpdate("UPDATE Queue SET connection = 'f' WHERE id = '" + id + "';");
        } catch (SQLException ex) {
            
        }
     }
    
    public int updateID(String id, int position) {
        try {
            
            if (!conn.isClosed()){
                stmnt = conn.createStatement(java.sql.ResultSet.TYPE_SCROLL_SENSITIVE, java.sql.ResultSet.CONCUR_UPDATABLE);
            }
           
            ResultSet rs = stmnt.executeQuery("SELECT position FROM Queue WHERE id ='" + id + "';");
            
            if (rs.next()){
               position = rs.getInt(1);
            }
            
            if (position == 0 && (!displayedConnectError)) {
                displayedConnectError = true;
                
            } else if (position > 0) {
                displayedConnectError = false;
              
            }
            stmnt.executeUpdate("UPDATE Queue SET timestamp=now() WHERE id='" + id + "';");
            rs.close();
            
            return position;
            
        } catch (SQLException ex) {
            return 0;
        }
    }
    
    /**
     * 
     * @return 
     */
    public String getHost() {
        return host;
    }

    /**
     * 
     * @return 
     */
    public String getPort() {
        return port;
    }

    /**
     * 
     * @return 
     */
    public String getUser() {
        return user;
    }

    /**
     * 
     * @return 
     */
    public String getPass() {
        return password;
    }

    /**
     * 
     * @param sql
     * @return 
     */
    public ResultSet executeSQLQuery(String sql) {
        try {
            if (!conn.isClosed()) {
                rs = stmnt.executeQuery(sql);
            }
        } catch (SQLException ex) {
        }
        return rs;
    }

    public void closeConnection() {
        try {
            conn.close();
        } catch (SQLException ex) {
            
        }
    }
}
